<template>
  <!--附件弹窗部分 -->
  <el-dialog  v-dialogDrag  
    :close-on-click-modal="false"
    :title="dialogStatus"
    :visible.sync="showappendix"
    width="80%"
    @close="notshow"
  >
      <div>
          <el-col
            style="text-align:right;margin-top: 0px;"
            :span="23"
          >
            <el-input v-model="filterName" 
              placeholder="请输入姓名或者附件过滤"
              
            />
             </el-col>
            </div>
    <el-form
      v-loading="previewloading"
      class="dialog-backgroundcolor"
    >
      <div style="float:right;margin-top:10px">
        <el-upload
          :show-file-list="showFileList"
          class="upload-demo"
          accept=".pdf"
          action="#"
          multiple
          :file-list="fileList"
          :http-request="uploadExcel"
           
        >
          <el-button
            v-if="display"
            size="small"
            type="primary"
          >上传附件</el-button>
        </el-upload>
         <el-button
            v-if="display"
            size="small"
            type="primary"
            @click="deleteFileBySelect"
          >批量删除</el-button>
      </div>
      <el-table
        ref="fileTable"
        v-loading="fileTableloading"
        :data="lists"
        stripe
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        style="width: 100%"
      >
        <template slot="empty">
          <tableEmpty />
        </template>
        <el-table-column
        type="selection"
        width="55"
        align="center"
        fixed
      />
        <el-table-column
          type="index"
          label="序号"
          width="180"
        />
        <el-table-column
          prop="middleTableCode"
          :label="Name"
        />
        <el-table-column
          prop="createTime"
          label="操作日期"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{ scope.row. createTime| parseTime('{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="fileName"
          label="文件"
        />
        <el-table-column
          label="操作"
          width="120"
        >
          <template slot-scope="row">
            <el-button
              type="text"
              size="small"
              @click="preview(row)"
            >预览</el-button>
            <el-button
              type="text"
              size="small"
              @click="downFile(row)"
            >下载</el-button>

            <el-button
              v-if="display"
              type="text"
              size="small"
              @click="deleteFile(row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row>
        <el-col
          :span="24"
          style="text-align: center; margin-top:20px;"
        >
          <el-button @click="notshow">
            关闭
          </el-button>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>
<script>
import tableEmpty from '@/components/table/empty'
import {
  queryExcel,
  Upload,
  attachmentPreservation,
  save,
  attachmentDownload,
  attachmentDelete,
  attachmentDeleteByIds
} from '@/api/baseInfo'
export default {
  components: { tableEmpty },
  props: ['middleTableCode'],
  data() {
    return {
      Name: '姓名',
      filterName:'',
      display: true,
      showappendix: false,
      // Table laoding刷新
      fileTableloading: false,
      // 全部 loading刷新
      previewloading: false,
      fileList: [],
      selectfileList: [],
      tableData: [],
      dialogStatus: '',
      allowFiles:'.pdf.PDF',
      savedata: {
        agencyId: this.$store.getters.userInfo.agencyId,
        billguid: '',
        fileId: '',
        fileName: '',
        middleTableCode: '',
        operateType: '',
        children: []
      },
      downLoadlist: {
        appid: 'salary',
        fileguid: ''
      },
      showFileList: false,
      List: [], 
      OperateList:[],
      file:''
      
    }
  },   
  computed: {  
    lists: function() {
      var search = this.filterName  
      if (search) {
        return this.List.filter(function(dataNews) {
          return Object.keys(dataNews).some(function(key) {
            if (key === 'middleTableCode'|| key === 'fileName') {
             return String(dataNews[key]).indexOf(search) > -1
            } 
          })
        })
      }
      // debugger
      return this.List
    }
  },
  watch: {},
  mounted() {},
  created() {},
  methods: {
    notshow() {
      this.showappendix = false
      this.$emit('upload', 1)
    },
    // 打开附件弹窗
    /**
     * selection：选中的数据
     * display：上传按钮和删除按钮是否显示
     * name：列名，默认【姓名】
     * agencyId：单位id，默认本单位id
     * operateType：操作类型，2：单位人员 1：财政单位  默认2
     */
    appendixOpen(selection, display, name, agencyId, operateType) {
      if (agencyId !== '' && agencyId !== null && agencyId !== undefined) {
        this.savedata.agencyId = agencyId
      }
      if (name === undefined) {
        this.Name = '姓名'
      } else {
        this.Name = name
      }
      if (operateType === undefined) {
        this.savedata.operateType = '2'
      } else {
        this.savedata.operateType = operateType
      }
      if (selection === undefined || selection.length === 0) {
        this.display = false
      } else {
        this.display = display
      }
      this.previewloading = false
      this.fileTableloading = false
      this.selection = selection
      this.List.splice(0, this.List.length)
      this.dialogStatus = '附件'
      this.showappendix = true
      //在附件要上传之前查询
      this.attachmentPreservation()
    },
    
    uploadExcel(item) {   
      let that=this
    const Lists=this.OperateList
      const fileObj = item.file
      // FormData 对象
      const form = new FormData()
      // 文件对象
     let arr= fileObj.name.split('.')
     let extension=arr[arr.length-1]
     if(this.allowFiles.indexOf(extension)<0){
       this.$message({
            showClose: true,
            message: '不允许的文件类型！',
            type: 'warning',
            duration: 4000
          })
       return 
      }
      for(let i=0;i<this.List.length;i++){
        if(that.List[i].fileName===fileObj.name){
            this.$message({
             showClose: true,
             message: that.List[i].middleTableCode+"附件已上传过"+that.List[i].fileName,
             type: 'warning',
             duration: 4000
           })
             this.fileTableloading = false
             
            return 
      }
    }
      const uuid = this.uuid()
      form.append('file', fileObj)
      form.append('appid', 'salary')
      form.append('billguid', uuid)
      this.fileTableloading = true
      this.List.splice(0, this.List.length)
      Upload(form).then(response => {
        if (response.rscode === '100000') {
          this.savedata.billguid = uuid
          this.savedata.middleTableCode = this.middleTableCode
          this.savedata.fileId = response.data
          this.savedata.fileName = fileObj.name
          this.save()
        } else if (response.rscode === '119000') {
          this.$message({
            showClose: true,
            message: '上传失败',
            type: 'error',
            duration: 0
          })
        }
      })
    },
    // 附件保存
    save() {
      
      this.savedata.children = []
      this.selection.forEach(item => {
        this.savedata.children.push(item.id)
      })
      this.savedata.children.join(',')
     
      save(this.savedata).then(response => {
        if (response.data === '100000') {
          this.$message({
            showClose: true,
            message: '上传附件成功',
            type: 'success',
            duration: 4000
          })
          
          this.fileTableloading = false
          this.attachmentPreservation()
        }
      })
      
    },
    // 附件查询
    attachmentPreservation() {
      this.fileTableloading = true
      const ids = []
      this.selection.forEach(item => {
        ids.push(item.id)
      })
      const queryList = {}
      queryList['list'] = ids.join(',')
      const params = {
        'list': ids,
        'agencyId': this.savedata.agencyId,
        'operateType': this.savedata.operateType
      }
      attachmentPreservation(params).then(response => {

        this.List = response.data
        this.fileTableloading = false
      })
    },

    // 下载附件
    downFile(row) {
      this.previewloading = true
      this.downLoadlist.fileguid = row.row.fileId
      // 文件对象
      attachmentDownload(this.downLoadlist).then(response => {
        const link = document.createElement('a')
        const objectUrl = URL.createObjectURL(response)
        link.href = objectUrl
        link.download = row.row.fileName
        link.click()
        URL.revokeObjectURL(objectUrl)
        this.previewloading = false
      })
    },
    // 附件删除
    deleteFile(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.previewloading = true
        attachmentDelete(row.row).then(response => {
          if (response.data === '100000') {
            this.$message({
              showClose: true,
              message: '删除成功',
              type: 'success',
              duration: 4000
            })
            this.previewloading = false
            this.attachmentPreservation()
            // this.$emit('upload', 1)
          }
        })
      })
    },
    // 附件批量删除
    deleteFileBySelect() {
      this.selectfileList=[]
      const selection = this.$refs.fileTable.selection
      if(selection.length==0){
        this.$message({
              message: '请选择要删除的附件',
              type: 'warning',
              duration: 4000
            })
            return
      }
       selection.forEach(item => {
        this.selectfileList.push(item.id)
      })
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.previewloading = true
        attachmentDeleteByIds(this.selectfileList).then(response => {
          if (response.data === '100000') {
            this.$message({
              showClose: true,
              message: '删除成功',
              type: 'success',
              duration: 4000
            })
            this.previewloading = false
            this.attachmentPreservation()
            // this.$emit('upload', 1)
          }
        })
      })
    },
    // 附件预览
    preview(row) {
      this.previewloading = true

      this.downLoadlist.fileguid = row.row.fileId
      // 文件对象
      attachmentDownload(this.downLoadlist).then(response => {
        const binaryData = []
        binaryData.push(response)
        // 获取blob链接
        const pdfUrl = window.URL.createObjectURL(
          new Blob(binaryData, { type: 'application/pdf' })
        )
        window.open(pdfUrl)
        this.previewloading = false
      })
    },
    // 生成uuid
    uuid() {
      var s = []
      var hexDigits = '0123456789abcdef'
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
      }
      s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = ''

      var uuid = s.join('')
      return uuid
    }
  }
}
</script>
